import java.util.PriorityQueue;

public class SmallestTrimmedNumbers {

    public int[] smallestTrimmedNumbers(String[] nums, int[][] queries) {
        int n = queries.length;
        int[] ans = new int[n];
        int index = 0;
        for (int[] ints : queries) {
            String[] temp = new String[nums.length];
            PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> {
                if (temp[a].compareTo(temp[b]) != 0) return temp[a].compareTo(temp[b]);
                return a - b;
            });
            System.arraycopy(nums, 0, temp, 0, nums.length);
            for (int i = 0; i < temp.length; i++) {
                temp[i] = temp[i].substring(temp[i].length() - ints[1]);
                heap.add(i);
            }
            for (int i = 1; i < ints[0]; i++) {
                heap.poll();
            }
            ans[index++] = heap.poll();
        }
        return ans;
    }
}
